<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/08/18
 * Time: 上午 9:00
 */
namespace app\common\model;

use think\Cache;
use think\Model;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;

ini_set("display_errors", "on");

class SMS extends Common
{
    static $acsClient = null;
    /**
     * 构造阿里客户端
     *
     * SMS constructor.
     * @param string $data
     */
    public function __construct($data = "")
    {
        parent::__construct($data);

    }

    /**
     * 发送验证码
     *
     * @param string $mobile 发送验证码的手机号
     */
    static public function sendCaptcha($mobile)
    {
        //创建客户端
        $client = new SMS();

        //captcha标识
        $cacheName = "captcha" . "-" . $mobile;

        //生成验证码
        $captcha = $client->generateCaptcha($cacheName);

        //结果
        $result = false;
        /*获取配置*/
        $sms_sign=config('sms.sms_sign');
        $templatecode=config('sms.templatecode');

        //阿里短信
        $result = $client->sendSms($sms_sign, $templatecode, $mobile, $templateParam = array("code"=>$captcha), $outId = null, $smsUpExtendCode = null);
        $arr=json_decode(json_encode($result),true);

        //发送成功
        if ($arr['Code']=="OK"||$arr['Code']=="ok")
        {
            //存储短信验证码
            Cache::store('redis')->set($cacheName, array(
                "captcha" => md5($captcha),
                "due_time" => time() + 10 * 60,
            ));

//            Cache::set($cacheName, array(
//                "captcha" => md5($captcha),
//                "due_time" => time() + 10 * 60,
//            ));
        }else{
            throw new DeveloperException('短信发送失败！');
        }
    }


    /**
     * 验证短信验证码
     *
     * @param string $mobile 收到验证码的手机号
     * @param string $captcha 短信验证码
     * @throws UserException
     */
    static public function verifyCaptcha($mobile, $captcha)
    {
        //captcha标识
        $cacheName = "captcha" . "-" . $mobile;

        //判断验证码是否存在
        if (!Cache::store('redis')->has($cacheName))
        {
            throw new UserException("验证码不正确！");
        }

        //获取存储的验证码
        $cache = Cache::store('redis')->get($cacheName);

        //验证码过期
        if ($cache["due_time"] < time())
        {
            //删除存储的验证码
            Cache::rm($cacheName);

            throw new UserException("验证码过期！");
        }
        //验证码错误
        elseif ($cache["captcha"] != md5($captcha))
        {
            throw new UserException("验证码错误！");
        }
        else
        {
            //删除存储的验证码
            Cache::store('redis')->rm($cacheName);
        }
    }

    /**
     * 生成短信验证码
     *
     * @param string $cacheName 验证码的名称
     * @return string
     * @throws UserException
     */
    private function generateCaptcha($cacheName)
    {

        if (!Cache::store('redis')->has($cacheName))
        {
            //生成验证码
            return random(6, true);
        }

        //验证码
        $captcha = Cache::store('redis')->get($cacheName);

        if ($captcha["due_time"] < time())
        {
            //删除原有验证码
            Cache::store('redis')->rm($cacheName);


            return random(6, true);
        }
        else
        {
            throw new UserException("验证码有效期为10分钟,请查看手机短信!");
        }
    }


    /**
     * 发送短信
     *
     * @param string $signName <p>
     * 必填, 短信签名，应严格"签名名称"填写，参考：<a href="https://dysms.console.aliyun.com/dysms.htm#/sign">短信签名页</a>
     * </p>
     * @param string $templateCode <p>
     * 必填, 短信模板Code，应严格按"模板CODE"填写, 参考：<a href="https://dysms.console.aliyun.com/dysms.htm#/template">短信模板页</a>
     * (e.g. SMS_0001)
     * </p>
     * @param string $phoneNumbers 必填, 短信接收号码 (e.g. 12345678901)
     * @param array|null $templateParam <p>
     * 选填, 假如模板中存在变量需要替换则为必填项 (e.g. Array("code"=>"12345", "product"=>"阿里通信"))
     * </p>
     * @param string|null $outId [optional] 选填, 发送短信流水号 (e.g. 1234)
     * @param string|null $smsUpExtendCode [optional] 选填，上行短信扩展码（扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段）
     * @return stdClass
     */
    public static function sendSms($signName, $templateCode, $phoneNumbers, $templateParam = null, $outId = null, $smsUpExtendCode = null) {


        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        // 必填，设置雉短信接收号码
        $request->setPhoneNumbers($phoneNumbers);

        // 必填，设置签名名称
        $request->setSignName($signName);

        // 必填，设置模板CODE
        $request->setTemplateCode($templateCode);

        // 可选，设置模板参数
        if($templateParam) {
            $request->setTemplateParam(json_encode($templateParam));
        }

        // 可选，设置流水号
        if($outId) {
            $request->setOutId($outId);
        }

        // 选填，上行短信扩展码
        if($smsUpExtendCode) {
            $request->setSmsUpExtendCode($smsUpExtendCode);
        }

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);

        // 打印请求结果


        return $acsResponse;

    }
    public static function getAcsClient() {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";


        $accessKeyId = config('sms.accesskeyid'); // AccessKeyId

        $accessKeySecret = config('sms.accesskeysecret'); // AccessKeySecret


        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if(static::$acsClient == null) {

            Config::load();

            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

}